package com.qbd.show.controller;

import com.qbd.show.biz.DownBiz;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

@Controller
public class DownController extends BaseController {

    @Resource
    private DownBiz downBiz;

    @RequestMapping(value="down",method = RequestMethod.POST)
    @ResponseBody
    public void domload(HttpServletResponse response, HttpServletRequest request) throws IOException  {
        response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600"); //设置过期时间
        response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, client_id, uuid, Authorization");
        response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // 支持HTTP 1.1.
        response.setHeader("Pragma", "no-cache"); // 支持HTTP 1.0. response.setHeader("Expires", "0");
        //获得请求文件名
        String path = request.getParameter("array");
        System.out.println(path);
        //以下载方式打开
        response.setHeader("Content-Disposition", "attachment;filename=java.pdf");
        File file = new File(path);
        FileInputStream fis =  new FileInputStream(file);
        //写出
        ServletOutputStream out = response.getOutputStream();
        //定义读取缓冲区
        byte buffer[] = new byte[1024];
        //定义读取长度
        int len = 1024;
        //循环读取
        while((len = fis.read(buffer))!=-1){
            out.write(buffer,0,len);
        }
        //释放资源
        fis.close();
        out.flush();
        out.close();
    }
}